<template>
  <div class="role-list">
    <a-card title="角色管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="角色名称">
            <a-input v-model:value="searchForm.name" placeholder="请输入角色名称" />
          </a-form-item>
          <a-form-item label="角色编码">
            <a-input v-model:value="searchForm.code" placeholder="请输入角色编码" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-area">
        <a-button type="primary" @click="handleAdd">
          <plus-outlined />
          新增角色
        </a-button>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="roleList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.statusName || (record.status === 1 ? '正常' : '禁用') }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button type="link" size="small" @click="handleView(record)">查看</a-button>
              <a-button type="link" size="small" @click="handlePermission(record)">权限</a-button>
              <a-popconfirm
                title="确定要删除这个角色吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 角色表单模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="角色名称" name="name">
              <a-input v-model:value="form.name" placeholder="请输入角色名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色编码" name="code">
              <a-input v-model:value="form.code" placeholder="请输入角色编码" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="排序" name="sort">
              <a-input-number v-model:value="form.sort" placeholder="请输入排序" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="form.status" placeholder="请选择状态">
                <a-select-option :value="1">正常</a-select-option>
                <a-select-option :value="0">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限分配模态框 -->
    <a-modal
      v-model:open="permissionModalVisible"
      title="分配权限"
      @ok="handlePermissionOk"
      @cancel="handlePermissionCancel"
      width="800px"
    >
      <a-tree
        v-model:checkedKeys="checkedKeys"
        v-model:expandedKeys="expandedKeys"
        :tree-data="menuTree"
        :field-names="{ title: 'title', key: 'id', children: 'children' }"
        checkable
        :default-expand-all="true"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getRolePage, addRole, updateRole, deleteRole } from '@/api/role'
import { getRoleMenus, updateRoleMenus, getUserMenus, getMenuTree } from '@/api/menu'
import { useUserStore } from '@/store/user'
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const roleList = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增角色')
const formRef = ref()

// 权限相关
const permissionModalVisible = ref(false)
const menuTree = ref([])
const checkedKeys = ref([])
const expandedKeys = ref([])
const currentRole = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 角色表单
const form = reactive({
  id: '',
  name: '',
  code: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '角色名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '角色编码',
    dataIndex: 'code',
    key: 'code'
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 280
  }
]

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      code: searchForm.code || undefined,
      status: searchForm.status || undefined
    }
    const res = await getRolePage(params)
    roleList.value = res.data.data.records || []
    pagination.total = res.data.data.total || 0
  } catch (error) {
    message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchRoleList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    status: ''
  })
  pagination.current = 1
  fetchRoleList()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchRoleList()
}

// 新增角色
const handleAdd = () => {
  modalTitle.value = '新增角色'
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    sort: 0,
    status: 1,
    remark: ''
  })
  modalVisible.value = true
}

// 编辑角色
const handleEdit = (record) => {
  modalTitle.value = '编辑角色'
  Object.assign(form, record)
  modalVisible.value = true
}

// 查看角色
const handleView = (record) => {
  modalTitle.value = '查看角色'
  Object.assign(form, record)
  modalVisible.value = true
}

// 删除角色
const handleDelete = async (record) => {
  try {
    const res = await deleteRole(record.id)
    if (res.data && res.data.code === 200) {
      message.success('删除成功')
      fetchRoleList()
    } else {
      message.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 权限管理
const handlePermission = async (record) => {
  currentRole.value = record
  try {
    // 1. 获取完整菜单树用于展示
    const menuRes = await getMenuTree()
    menuTree.value = menuRes.data.data || []

    // 2. 获取当前用户拥有的菜单ID列表
    const userMenuRes = await getUserMenus(userStore.user.id)
    const userMenus = userMenuRes.data.data || []
    const userMenuIds = new Set(userMenus.map(item => String(item.id)))

    // 3. 获取角色已分配的权限ID
    const roleMenuRes = await getRoleMenus(record.id)
    const roleMenus = roleMenuRes.data.data || []
    // 只回显当前用户有的权限
    checkedKeys.value = roleMenus.map(item => String(item.id)).filter(id => userMenuIds.has(id))

    // 展开所有节点
    function getAllKeys(tree) {
      let keys = [];
      tree.forEach(node => {
        keys.push(String(node.id));
        if (node.children && node.children.length) {
          keys = keys.concat(getAllKeys(node.children));
        }
      });
      return keys;
    }
    expandedKeys.value = getAllKeys(menuTree.value);

    permissionModalVisible.value = true
  } catch (error) {
    message.error('获取权限数据失败')
    console.error('handlePermission error:', error)
  }
}

// 权限确认
const handlePermissionOk = async () => {
  try {
    const res = await updateRoleMenus(currentRole.value.id, checkedKeys.value)
    if (res.data && res.data.code === 200) {
      message.success('权限分配成功')
      permissionModalVisible.value = false
      checkedKeys.value = []
      currentRole.value = null
    } else {
      message.error(res.data?.message || '权限分配失败')
    }
  } catch (error) {
    message.error('权限分配失败')
  }
}

// 权限取消
const handlePermissionCancel = () => {
  permissionModalVisible.value = false
  currentRole.value = null
  checkedKeys.value = []
}

// 模态框确认
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    let res
    if (form.id) {
      res = await updateRole(form)
      if (res.data && res.data.code === 200) {
        message.success('更新成功')
      } else {
        message.error(res.data?.message || '更新失败')
        return
      }
    } else {
      res = await addRole(form)
      if (res.data && res.data.code === 200) {
        message.success('添加成功')
      } else {
        message.error(res.data?.message || '添加失败')
        return
      }
    }
    modalVisible.value = false
    fetchRoleList()
  } catch (error) {
    message.error('表单提交失败')
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-list {
  padding: 24px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.action-area {
  margin-bottom: 16px;
}

@media (max-width: 600px) {
  .role-list {
    padding: 4px !important;
  }
  .search-area {
    padding: 8px !important;
    margin-bottom: 8px !important;
    flex-direction: column !important;
  }
  .action-area {
    margin-bottom: 8px !important;
  }
  .ant-table {
    font-size: 12px !important;
    overflow-x: auto !important;
    min-width: 480px;
  }
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 4px 6px !important;
  }
  .ant-modal {
    width: 96vw !important;
    max-width: 96vw !important;
    min-width: 0 !important;
  }
}
</style> 